package sql;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import sql.record.*;
public class SearchUtility {

	private final static String days[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday"};

	public static List<TableRecord> searchDB(String username,List<String> Keywords) throws ClassNotFoundException, SQLException{
		User user = new User();
		user.userName = username;
		List<TableRecord> courseSchedList = DBManagment.getAvailableCourses(user);
		List<Course> courses = new LinkedList<Course>();
		
		//creating course list
		for(TableRecord t: courseSchedList){
			if(t instanceof Course){
				int lastIndex = courses.size() - 1;
				Course currentCourse = (Course)t;
				if((lastIndex == -1) || (!courses.get(lastIndex).courseName.equals(currentCourse.courseName))){
					courses.add((Course)t);
				}
			}
		}
		
		Map<Course, Integer> tempResults = new HashMap<Course, Integer>();
		ValueComparator vc = new ValueComparator(tempResults);
		SortedMap<Course, Integer> sortedTempResults = new TreeMap<Course, Integer>(vc); 
		
		//searching courses
		for(Course c: courses){
			int count = 0;

			//searching
			for(String s: Keywords){
				//search via course fields...
				for(Field field: c.getClass().getFields()){
					Object fieldVal = null;
					try {
						fieldVal = field.get(c);
					} catch (Exception e) {
						//something is wrong with java.....
					}
					if (fieldVal instanceof String)
					{
						if(((String)fieldVal).contains(s)){
							count++;
						}
					}else if(fieldVal instanceof Integer){
						if(((Integer)fieldVal).toString().contains(s)){
							count++;
						}
					}
					
				}
				
				//search for a day.....
				for(TableRecord t : courseSchedList){
					if(t instanceof CourseSchedule){
						if(((CourseSchedule)t).courseName.equals(c.courseName)){
							if(days[((CourseSchedule)t).day].contains(s)){
								count++;
							}
						}
					}
				}
			}
			
			//adding to the temp results if fount suitable (+rank)
			if(count != 0){
				tempResults.put(c, new Integer(count));
			}
		}
		
		//sorting
		sortedTempResults.putAll(tempResults);
		
		//creating result format
		List<TableRecord> results = new LinkedList<TableRecord>();
		for(Course c: sortedTempResults.keySet()){
			for(TableRecord t: courseSchedList){
				if(t instanceof CourseSchedule){
					if(((CourseSchedule)t).courseName.equals(c.courseName)){
						results.add(c);
						results.add(t);						
					}
				}
			}
		}
		return results;
	}
	
	

}